﻿using System;
using System.Threading;
using System.Web;
using System.Web.UI;
using UDS.Components;

namespace UDS.WebApp
{
    public class PageBase : Page
    {
        private int _hasEnoughPermission;

        /// <summary>
        /// Determines whether the current user has the permission specified in <see cref="RequiredPermission"/>.
        /// </summary>
        protected bool HasEnoughPermission
        {
            get
            {
                if (PermissionType.None == RequiredPermission)
                {
                    return true;
                }
#if DEBUG
                // Verify only the predefined permission is used
                if (!Enum.IsDefined(typeof(PermissionType), RequiredPermission))
                {
                    throw new InvalidOperationException(string.Format("'{0}' is not a well-known permission.", RequiredPermission));
                }
#endif

                const int NotSet = 0;
                const int CAN = 1;
                const int CANNOT = 2;
                SiteContext context = SiteContext.Current;

                if (_hasEnoughPermission == NotSet)
                {
                    if (!context.IsAuthenticated)
                    {
                        _hasEnoughPermission = CANNOT;
                    }
                    else
                    {
                        Interlocked.CompareExchange(
                            ref _hasEnoughPermission,
                            AssignRights.IsAccessAllowed(context.UserName, context.ActiveNodeID, RequiredPermission) ? CAN : CANNOT,
                            NotSet);
                    }
                }
                return _hasEnoughPermission == CAN;
            }
        }

        /// <summary>
        /// Specifies the minimal permission required to access this page.
        /// </summary>
        public virtual PermissionType RequiredPermission
        {
            get { return PermissionType.None; }
        }

        protected override void OnInit(EventArgs e)
        {
            if (!HasEnoughPermission)
            {
                throw new InvalidOperationException("You do not have enough permission to visit this page.");
            }

            base.OnInit(e);
        }
    }
}
